package pdd;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.PriorityQueue;

public class Main {

    public static void main(String[] args) throws Exception{
        BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
        String s = buf.readLine();
        String[] ss;
        int T = Integer.parseInt(s);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < T; i++){
            int day = 1;
            int res = 0;
            PriorityQueue<Node> heap = new PriorityQueue<Node>((n1, n2)->{
                if (n1.score != n2.score){
                    return n2.score - n1.score;
                }
                return n1.endDay - n2.endDay;
            });
            s = buf.readLine();
            int N = Integer.parseInt(s);
            for (int j = 0; j < N; j++){
                s = buf.readLine();
                ss = s.split(" ");
                int score = Integer.parseInt(ss[0]);
                int endDay = Integer.parseInt(ss[1]);
                heap.offer(new Node(score, endDay));
            }
            while (!heap.isEmpty()){
                Node node = heap.peek();
                if (node.endDay < day){
                    heap.poll();
                    continue;
                } else {
                    res += node.score;
                    heap.poll();
                    day++;
                }
            }
            sb.append(res).append("\n");
        }
        System.out.print(sb.toString());
    }
}
class Node{
    int score;
    int endDay;

    Node(int score, int endDay){
        this.score = score;
        this.endDay = endDay;
    }
}
